import { apiService } from './api';

// 通知相关类型定义
export interface NotificationItem {
  id: string;
  title: string;
  content: string;
  type: 'info' | 'success' | 'warning' | 'error' | 'system';
  category: string;
  priority: 'low' | 'medium' | 'high' | 'urgent';
  status: 'unread' | 'read' | 'archived';
  recipientId: string;
  recipientName: string;
  senderId?: string;
  senderName?: string;
  sourceType: 'system' | 'user' | 'workflow' | 'task' | 'form';
  sourceId?: string;
  channels: NotificationChannel[];
  templateId?: string;
  variables?: Record<string, any>;
  scheduledAt?: string;
  sentAt?: string;
  readAt?: string;
  archivedAt?: string;
  createdAt: string;
  updatedAt: string;
  actions?: NotificationAction[];
  metadata?: Record<string, any>;
}

export interface NotificationAction {
  id: string;
  label: string;
  type: 'button' | 'link';
  action: string;
  url?: string;
  style?: 'primary' | 'secondary' | 'danger';
  icon?: string;
}

export interface NotificationChannel {
  type: 'in_app' | 'email' | 'sms' | 'push' | 'webhook';
  status: 'pending' | 'sent' | 'failed' | 'delivered';
  sentAt?: string;
  deliveredAt?: string;
  error?: string;
  config?: Record<string, any>;
}

export interface NotificationTemplate {
  id: string;
  name: string;
  description: string;
  category: string;
  type: NotificationItem['type'];
  channels: NotificationChannel['type'][];
  subject: string;
  content: string;
  variables: TemplateVariable[];
  isActive: boolean;
  createdBy: string;
  createdByName: string;
  createdAt: string;
  updatedAt: string;
}

export interface TemplateVariable {
  name: string;
  type: 'string' | 'number' | 'boolean' | 'date' | 'object';
  description: string;
  required: boolean;
  defaultValue?: any;
  example?: any;
}

export interface NotificationRule {
  id: string;
  name: string;
  description: string;
  isActive: boolean;
  trigger: NotificationTrigger;
  conditions: NotificationCondition[];
  actions: NotificationRuleAction[];
  priority: number;
  createdBy: string;
  createdByName: string;
  createdAt: string;
  updatedAt: string;
}

export interface NotificationTrigger {
  type: 'event' | 'schedule' | 'condition';
  event?: string;
  schedule?: {
    type: 'once' | 'recurring';
    datetime?: string;
    cron?: string;
    timezone?: string;
  };
  condition?: {
    field: string;
    operator: 'equals' | 'not_equals' | 'contains' | 'greater_than' | 'less_than';
    value: any;
  };
}

export interface NotificationCondition {
  field: string;
  operator: 'equals' | 'not_equals' | 'contains' | 'greater_than' | 'less_than' | 'in' | 'not_in';
  value: any;
  logicalOperator?: 'and' | 'or';
}

export interface NotificationRuleAction {
  type: 'send_notification' | 'send_email' | 'send_sms' | 'webhook' | 'create_task';
  templateId?: string;
  recipients: NotificationRecipient[];
  channels: NotificationChannel['type'][];
  config?: Record<string, any>;
}

export interface NotificationRecipient {
  type: 'user' | 'role' | 'group' | 'email';
  id?: string;
  email?: string;
  name?: string;
}

export interface NotificationSubscription {
  id: string;
  userId: string;
  userName: string;
  category: string;
  channels: NotificationChannel['type'][];
  isActive: boolean;
  preferences: {
    frequency: 'immediate' | 'hourly' | 'daily' | 'weekly';
    quietHours?: {
      start: string;
      end: string;
      timezone: string;
    };
    priority: NotificationItem['priority'][];
  };
  createdAt: string;
  updatedAt: string;
}

export interface NotificationStats {
  total: number;
  unread: number;
  read: number;
  archived: number;
  byType: Record<NotificationItem['type'], number>;
  byCategory: Record<string, number>;
  byChannel: Record<NotificationChannel['type'], number>;
  recentActivity: {
    sent: number;
    delivered: number;
    failed: number;
  };
}

export interface NotificationSearchParams {
  keyword?: string;
  type?: NotificationItem['type'];
  category?: string;
  status?: NotificationItem['status'];
  priority?: NotificationItem['priority'];
  senderId?: string;
  sourceType?: NotificationItem['sourceType'];
  dateRange?: {
    start: string;
    end: string;
  };
  page?: number;
  size?: number;
  sortBy?: 'createdAt' | 'sentAt' | 'readAt' | 'priority';
  sortOrder?: 'asc' | 'desc';
}

// 通知服务类
class NotificationService {
  // 获取通知列表
  async getNotifications(params?: NotificationSearchParams): Promise<{
    content: NotificationItem[];
    totalElements: number;
    totalPages: number;
    size: number;
    number: number;
  }> {
    return apiService.get('/notifications', params);
  }

  // 获取通知详情
  async getNotification(id: string): Promise<NotificationItem> {
    return apiService.get(`/notifications/${id}`);
  }

  // 发送通知
  async sendNotification(notification: {
    title: string;
    content: string;
    type?: NotificationItem['type'];
    category?: string;
    priority?: NotificationItem['priority'];
    recipients: NotificationRecipient[];
    channels?: NotificationChannel['type'][];
    templateId?: string;
    variables?: Record<string, any>;
    scheduledAt?: string;
    actions?: Omit<NotificationAction, 'id'>[];
    metadata?: Record<string, any>;
  }): Promise<NotificationItem> {
    return apiService.post('/notifications', notification);
  }

  // 批量发送通知
  async sendBatchNotifications(notifications: Parameters<typeof this.sendNotification>[0][]): Promise<NotificationItem[]> {
    return apiService.post('/notifications/batch', { notifications });
  }

  // 标记为已读
  async markAsRead(id: string): Promise<void> {
    return apiService.put(`/notifications/${id}/read`);
  }

  // 批量标记为已读
  async markBatchAsRead(ids: string[]): Promise<void> {
    return apiService.put('/notifications/batch/read', { ids });
  }

  // 标记全部为已读
  async markAllAsRead(): Promise<void> {
    return apiService.put('/notifications/all/read');
  }

  // 归档通知
  async archiveNotification(id: string): Promise<void> {
    return apiService.put(`/notifications/${id}/archive`);
  }

  // 批量归档
  async archiveBatchNotifications(ids: string[]): Promise<void> {
    return apiService.put('/notifications/batch/archive', { ids });
  }

  // 删除通知
  async deleteNotification(id: string): Promise<void> {
    return apiService.delete(`/notifications/${id}`);
  }

  // 批量删除
  async deleteBatchNotifications(ids: string[]): Promise<void> {
    return apiService.post('/notifications/batch/delete', { ids });
  }

  // 获取未读通知数量
  async getUnreadCount(): Promise<number> {
    const response: { count: number } = await apiService.get('/notifications/unread/count');
    return response.count;
  }

  // 获取通知统计
  async getNotificationStats(): Promise<NotificationStats> {
    return apiService.get('/notifications/stats');
  }

  // 通知模板管理
  async getTemplates(params?: {
    category?: string;
    type?: NotificationItem['type'];
    isActive?: boolean;
    page?: number;
    size?: number;
  }): Promise<{
    content: NotificationTemplate[];
    totalElements: number;
    totalPages: number;
    size: number;
    number: number;
  }> {
    return apiService.get('/notifications/templates', params);
  }

  async getTemplate(id: string): Promise<NotificationTemplate> {
    return apiService.get(`/notifications/templates/${id}`);
  }

  async createTemplate(template: Omit<NotificationTemplate, 'id' | 'createdBy' | 'createdByName' | 'createdAt' | 'updatedAt'>): Promise<NotificationTemplate> {
    return apiService.post('/notifications/templates', template);
  }

  async updateTemplate(id: string, template: Partial<NotificationTemplate>): Promise<NotificationTemplate> {
    return apiService.put(`/notifications/templates/${id}`, template);
  }

  async deleteTemplate(id: string): Promise<void> {
    return apiService.delete(`/notifications/templates/${id}`);
  }

  // 通知规则管理
  async getRules(params?: {
    isActive?: boolean;
    page?: number;
    size?: number;
  }): Promise<{
    content: NotificationRule[];
    totalElements: number;
    totalPages: number;
    size: number;
    number: number;
  }> {
    return apiService.get('/notifications/rules', params);
  }

  async getRule(id: string): Promise<NotificationRule> {
    return apiService.get(`/notifications/rules/${id}`);
  }

  async createRule(rule: Omit<NotificationRule, 'id' | 'createdBy' | 'createdByName' | 'createdAt' | 'updatedAt'>): Promise<NotificationRule> {
    return apiService.post('/notifications/rules', rule);
  }

  async updateRule(id: string, rule: Partial<NotificationRule>): Promise<NotificationRule> {
    return apiService.put(`/notifications/rules/${id}`, rule);
  }

  async deleteRule(id: string): Promise<void> {
    return apiService.delete(`/notifications/rules/${id}`);
  }

  async toggleRule(id: string, isActive: boolean): Promise<NotificationRule> {
    return apiService.put(`/notifications/rules/${id}/toggle`, { isActive });
  }

  // 订阅管理
  async getSubscriptions(): Promise<NotificationSubscription[]> {
    return apiService.get('/notifications/subscriptions');
  }

  async getSubscription(category: string): Promise<NotificationSubscription> {
    return apiService.get(`/notifications/subscriptions/${category}`);
  }

  async updateSubscription(category: string, subscription: Partial<NotificationSubscription>): Promise<NotificationSubscription> {
    return apiService.put(`/notifications/subscriptions/${category}`, subscription);
  }

  async createSubscription(subscription: Omit<NotificationSubscription, 'id' | 'userId' | 'userName' | 'createdAt' | 'updatedAt'>): Promise<NotificationSubscription> {
    return apiService.post('/notifications/subscriptions', subscription);
  }

  async deleteSubscription(category: string): Promise<void> {
    return apiService.delete(`/notifications/subscriptions/${category}`);
  }

  // 实时通知相关
  async connectWebSocket(): Promise<WebSocket> {
    const wsUrl = `ws://localhost:8080/ws/notifications`;
    const ws = new WebSocket(wsUrl);
    
    ws.onopen = () => {
      console.log('通知WebSocket连接已建立');
    };
    
    ws.onerror = (error) => {
      console.error('通知WebSocket连接错误:', error);
    };
    
    ws.onclose = () => {
      console.log('通知WebSocket连接已关闭');
    };
    
    return ws;
  }

  // 测试通知
  async testNotification(config: {
    type: NotificationChannel['type'];
    recipient: string;
    templateId?: string;
    variables?: Record<string, any>;
  }): Promise<{ success: boolean; message: string }> {
    return apiService.post('/notifications/test', config);
  }

  // 获取通知历史
  async getNotificationHistory(params?: {
    startDate?: string;
    endDate?: string;
    type?: NotificationItem['type'];
    status?: 'sent' | 'delivered' | 'failed';
    page?: number;
    size?: number;
  }): Promise<{
    content: NotificationItem[];
    totalElements: number;
    totalPages: number;
    size: number;
    number: number;
  }> {
    return apiService.get('/notifications/history', params);
  }

  // 重发失败的通知
  async retryFailedNotification(id: string): Promise<NotificationItem> {
    return apiService.post(`/notifications/${id}/retry`);
  }

  // 获取通知分类
  async getCategories(): Promise<string[]> {
    return apiService.get('/notifications/categories');
  }

  // 导出通知数据
  async exportNotifications(params?: {
    format: 'csv' | 'excel' | 'json';
    startDate?: string;
    endDate?: string;
    type?: NotificationItem['type'];
    status?: NotificationItem['status'];
  }): Promise<Blob> {
    return apiService.get('/notifications/export', params);
  }
}

export const notificationService = new NotificationService();
export default notificationService;